package com.ocom.nettyxf.aspect;

import cn.hutool.core.util.HexUtil;
import com.alibaba.fastjson.JSON;
import com.ocom.common.utils.NumConvertUtil;
import com.ocom.nettyxf.ropo.TcpServiceRopo;
import com.ocom.redis.util.RedisUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Aspect
@Component
public class ServiceAspect {

	private Logger log = LoggerFactory.getLogger(ServiceAspect.class);

	@Resource
	private RedisUtil redisUtil;

	//切入点
	@Around("execution(* com.ocom.nettyxf.service.impl.XfServerImpl.*(..)) " +
//			"|| execution(* com.ocom.ugcapi.controller.SignController.signList(..))  " +
			"|| execution(* com.ocom.nettyxf.service.impl.PayServerImpl.*(..)) ")
	public Object handleControllerMethod(ProceedingJoinPoint pjp) throws Throwable {
		// 类名
		String className = pjp.getTarget().getClass().getName();
		//方法名
		String methodName = pjp.getSignature().getName();
		try {
			Object[] args = pjp.getArgs();

			Object object=args[0];

			TcpServiceRopo tcpServiceRopo = JSON.parseObject(JSON.toJSONString(object),TcpServiceRopo.class);

			String sessionId=(String) redisUtil.hmGet("tcpXfMach:" + tcpServiceRopo.getMachId(), "sessionId");

			if(sessionId==null || !sessionId.equals(tcpServiceRopo.getSessionId())){
//				System.out.println("正确的sessionId :" + sessionId);
//				System.out.println("错误的sessionId :" + tcpServiceRopo.getSessionId());
				tcpServiceRopo.setRespTip("02");
				tcpServiceRopo.setCommandParam("0001");
				String rc = tcpServiceRopo.getHexStr();
				return HexUtil.decodeHex(rc);
			}
			Long start = System.currentTimeMillis();
			byte[] ob =(byte[]) pjp.proceed(args);
			Long end = System.currentTimeMillis();
			if(ob==null){
				log.info("消费TCP - aspect className【{}】methodName【{}】请求 【{}】返回【{}】耗时 【{}】",className,methodName,tcpServiceRopo,"返回null",end-start);
				return null;
			}
			log.info("消费TCP - aspect className【{}】methodName【{}】请求 【{}】返回【{}】耗时 【{}】",className,methodName,tcpServiceRopo, NumConvertUtil.bytesToHexString(ob),end-start);
			return ob;
		} catch (Exception e) {
			log.info("请求URL:,切面异常:【{}】【{}】【{}】",className,methodName, e);
			//要返回的对象
//			return HexUtil.decodeHex("5000");
			return null;
		}
	}


}
